package com.nescafe.nescafepromo.controller;

import java.util.Map;

import com.nescafe.nescafepromo.command.Command;
import com.nescafe.nescafepromo.command.CommandException;
import com.nescafe.nescafepromo.command.CommandType;
import com.nescafe.nescafepromo.model.NPRequest;
import com.nescafe.nescafepromo.model.NPResponse;

public abstract class Controller {

	protected ControllerType type = null;

	protected abstract void escapeCharacters(NPRequest req) throws ControllerException;

	protected abstract void validate(NPRequest req) throws ControllerException;

	protected abstract Command getCommand(CommandType commandType) throws ControllerException;

	private void securityCheck(NPRequest req) throws ControllerException {
		// if (req.getCommand().isSecured()) {
		// if (!req.isLogin() && !req.isAdminNPRequest()) {
		// throw new ControllerException("not logged in.");
		// }
		// }
	}

	private void checkRequiredParams(NPRequest req) throws ControllerException {
		CommandType comType = req.getCommand();
		String[] requiredParams = comType.getRequiredParams();
		Map<String, String> params = req.getParams();
		for (String requiredParam : requiredParams) {
			if (!params.containsKey(requiredParam)) {
				throw new ControllerException("invalid parameter");
			}
		}
	}

	public NPResponse process(NPRequest req) {
		NPResponse NPResponse = null;
		try {
			if (req.hasError()) {
				throw new ControllerException("invalid NPRequest format.");
			}
			securityCheck(req);
			checkRequiredParams(req);
			validate(req);
			escapeCharacters(req);
			Command cmd = getCommand(req.getCommand());
			NPResponse = cmd.execute(req);
		} catch (CommandException e) {
			return new NPResponse(e);
		} catch (ControllerException e) {
			return new NPResponse(e);
		}
		return NPResponse;
	}
}
